package cn.bon.schedule.service.impl;

import cn.bon.common.exception.BizIllegalException;
import cn.bon.schedule.api.pojo.dto.WorkOrderDTO;
import cn.bon.schedule.api.pojo.dto.WorkOrderDetailsDTO;
import cn.bon.schedule.api.pojo.vo.WorkOrderVO;
import cn.bon.schedule.api.pojo.po.RulesWorkOrder;
import cn.bon.schedule.mapper.RulesWorkOrderMapper;
import cn.bon.schedule.api.pojo.po.WorkOrderDetail;
import cn.bon.schedule.service.RulesWorkOrderService;
import cn.bon.schedule.service.WorkOrderDetailService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 班次管理 服务实现类
 * </p>
 *
 * @author LuoChao
 * @since 2023-12-14
 */
@Service
public class RulesWorkOrderServiceImpl extends ServiceImpl<RulesWorkOrderMapper, RulesWorkOrder> implements RulesWorkOrderService {

    @Resource
    WorkOrderDetailService detailService;

    /**
     * 新增班次
     *
     * @param dto
     */
    @Override
    @Transactional
    public void add(WorkOrderDTO dto) {
        RulesWorkOrder workOrder = new RulesWorkOrder();
        BeanUtils.copyProperties(dto, workOrder);

        // 填充timeInfo
        String timInfo = calcuTimeInfo(dto);
        workOrder.setTimeInfo(timInfo);

        //保存班次基本信息
        this.save(workOrder);
        // ID回填，获取ID
        Long workOrderId = workOrder.getWorkOrderId();

        //保存详情
        List<WorkOrderDetailsDTO> details = dto.getDetails();
        saveDetails(workOrderId,details);
    }

    /**
     * 保存班次详情
     * @param workOrderId
     * @param details
     */
    private void saveDetails(Long workOrderId, List<WorkOrderDetailsDTO> details) {
        if (details == null) throw new BizIllegalException("新增失败，请指定起始时间！");
        for (WorkOrderDetailsDTO detail : details) {
            WorkOrderDetail saveDetail = new WorkOrderDetail();
            BeanUtils.copyProperties(detail, saveDetail);
            saveDetail.setWorkOrderId(workOrderId);
            detailService.save(saveDetail);
        }
    }


    /**
     * 计算timeInfo
     *
     * @param dto
     * @return
     */
    private String calcuTimeInfo(WorkOrderDTO dto) {
        String timeInfo = "";
        List<WorkOrderDetailsDTO> details = dto.getDetails();

        if (dto.getWorkType().getValue().equals("排班制")) {
            WorkOrderDetailsDTO detail = details.get(0);
            if (detail == null) throw new BizIllegalException("排班错误，请指定起始时间");
            String start = detail.getTimeStart().format(DateTimeFormatter.ofPattern("hh:mm"));
            String end = detail.getTimeEnd().format(DateTimeFormatter.ofPattern("hh:mm"));

            timeInfo = start + " - " + end;
        } else if (dto.getWorkType().getValue().equals("固定班制")) {
            String[] workDay = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};

            List<String> collect = details.stream().map(detail -> {
                Integer dayCount = detail.getWeek();
                if (dayCount > 6) throw new BizIllegalException("班次天数错误");
                return workDay[dayCount];
            }).collect(Collectors.toList());
            timeInfo = String.join(",", collect);

        } else if (dto.getWorkType().getValue().equals("轮班制")) {
            timeInfo = "-";
        } else {
            throw new BizIllegalException("请指定正确的排班类型");
        }

        return timeInfo;
    }

    /**
     * 分页查询
     *
     * @param page
     * @param name
     * @param workType
     * @return
     */
    @Override
    public Page<RulesWorkOrder> doPage(Page<RulesWorkOrder> page, String name, String workType) {
        LambdaQueryWrapper<RulesWorkOrder> queryWrapper = new LambdaQueryWrapper<>();

        //查询条件
        queryWrapper.like(StrUtil.isNotBlank(name), RulesWorkOrder::getWorkOrderName, name);
        queryWrapper.eq(StrUtil.isNotBlank(workType), RulesWorkOrder::getWorkType, workType);

        return this.page(page, queryWrapper);
    }

    /**
     * 修改班次 数据回显
     * @param id
     * @return
     */
    @Override
    public WorkOrderVO getDetail(Long id) {
        WorkOrderVO vo = new WorkOrderVO();

        //查询基本信息
        RulesWorkOrder workOrder = this.getById(id);
        BeanUtils.copyProperties(workOrder, vo);

        LambdaQueryWrapper<WorkOrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkOrderDetail::getWorkOrderId, id);

        List<WorkOrderDetail> list = detailService.list(queryWrapper);
        vo.setDetails(list);

        return vo;
    }

    /**
     * 修改班次
     * @param id
     * @param dto
     */
    @Override
    @Transactional
    public void edit(Long id, WorkOrderDTO dto) {

        //填充workOrder的属性和ID
        RulesWorkOrder workOrder = new RulesWorkOrder();
        BeanUtils.copyProperties(dto, workOrder);
        workOrder.setWorkOrderId(id);
        // 填充timeInfo
        String timInfo = calcuTimeInfo(dto);
        workOrder.setTimeInfo(timInfo);
        //保存workOrder
        this.updateById(workOrder);

        //删除原有detail
        LambdaQueryWrapper<WorkOrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkOrderDetail::getWorkOrderId, id);
        detailService.remove(queryWrapper);
        //保存新的detail
        saveDetails(id, dto.getDetails());
    }

    /**
     * 删除班次
     * @param id
     */
    @Override
    public void detele(Long id) {
        //删除detail
        LambdaQueryWrapper<WorkOrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkOrderDetail::getWorkOrderId, id);
        detailService.remove(queryWrapper);

        //删除班次
        this.removeById(id);
    }
}
